/**
 * @作者:黎谢之
 * @创建时间：2021/7/13
 * @修改时间：2021/7/14
 */
package com.example.senior_bug.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.example.senior_bug.EntityClass.*;
import com.example.senior_bug.Repository.*;
import com.example.senior_bug.ToolClass.Result;
import com.example.senior_bug.enm.MsgId;
import com.example.senior_bug.utils.OrderUUIDUtils;
import com.example.senior_bug.utils.ResultUtils;
import com.example.senior_bug.utils.ToolUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Service
public class OrderService {
    @Autowired
    private CommentRepository commentRepository;
    @Autowired
    private PointRepository pointRepository;
    @Autowired
    private OrderRepository orderRepository;
    @Autowired
    private CustomerRepository customerRepository;
    @Autowired
    private SKURepository skuRepository;
    @Autowired
    private BusinessRepository businessRepository;
    @Autowired
    private AddressRepository addressRepository;
    @Autowired
    private BrandRepository brandRepository;
    @Autowired
    private GoodRepository goodRepository;
    @Autowired
    private CategoryRepository categoryRepository;
    @Autowired
    private ChannelRepository channelRepository;
    @Autowired
    private TemporaryAddressRepository temporaryAddressRepository;

    /*用户下订单
     * 1.Order对象(order)
     * 7.14修改商家名为店铺名
     * */
    public Result orderNewOrder(Order order, int addressId) {

        SKU sku = skuRepository.findById(order.getSku().getId());//获取SKU
        sku.setSales(sku.getSales() + 1);
        sku.getSkuSpecificationOptions().get(order.getSpecificationIndex()).setStock(sku.getSkuSpecificationOptions().get(order.getSpecificationIndex()).getStock()-1);
        Business business = businessRepository.findById(sku.getBusinessId());//获取商家对象
        Address address = addressRepository.findById(addressId);//获取地址
        Brand brand = brandRepository.findById(goodRepository.findById(sku.getGoodId()).getBrandId());//获取品牌
        Category category = categoryRepository.findById(brand.getCategoryId());//获取二级分类
        Channel channel = channelRepository.findById(category.getChannelId());//获取一级分类

        TemporaryAddress temporaryAddress = new TemporaryAddress();

        temporaryAddress.setArea(address.getArea());
        temporaryAddress.setAreaNum(address.getAreaNum());
        temporaryAddress.setProvince(address.getProvince());
        temporaryAddress.setProvinceNum(address.getProvinceNum());
        temporaryAddress.setCity(address.getCity());
        temporaryAddress.setCityNum(address.getCityNum());
        temporaryAddress.setTown(address.getTown());
        temporaryAddress.setTownNum(address.getTownNum());
        temporaryAddress.setDetailInfo(address.getDetailInfo());
        temporaryAddress.setReceiverName(address.getReceiverName());
        temporaryAddress.setPhoneNum(address.getPhoneNum());

        TemporaryAddress temporaryAddress1 = temporaryAddressRepository.saveAndFlush(temporaryAddress);


        order.setSku(sku);//设置sku
        order.setCustomerTemporaryAddress(temporaryAddress1);//设置地址
        order.setBusinessId(business.getId());//设置商家ID
        order.setBrandName(brand.getName());//设置品牌名字
        order.setStoreName(business.getStoreName());//设置店铺名字
        order.setCategoryName(category.getName());//设置二级分类名字
        order.setChannelName(channel.getName());//设置一级分类名字
        order.setUuid(OrderUUIDUtils.createOrderId());//设置订单编号


        Order order1 = orderRepository.saveAndFlush(order);

        business.getOrders().add(order1);//设置商家与订单的关联
        businessRepository.saveAndFlush(business);
        Customer customer = customerRepository.findById(order1.getCustomerId());
        customer.getOrders().add(order1);//设置用户与订单的关联
        customer.setDeliveredOrder(customer.getDeliveredOrder() + 1);
        customerRepository.saveAndFlush(customer);

        if (businessRepository.findById(business.getId()).getOrders().contains(order1) &&
                customerRepository.findById(customer.getId()).getOrders().contains(order1)) {
            return ResultUtils.success(true);
        } else {
            return ResultUtils.error(MsgId.ADD_ORDER_FAILED);
        }

    }

    /*用户订单界面
     * 1.用户昵称(CustomerName)
     * 获取Order的List
     * */
    public Result getOrderByCustomerName(String CustomerName) {
        //判断用户是否存在
        if (customerRepository.existsByName(CustomerName)) {
            Customer customer = customerRepository.findByName(CustomerName);
            List<Order> orders = orderRepository.findAllByCustomerId(customer.getId());

            if (orders.size() != 0) {
                return ResultUtils.success(JSON.parseArray(JSON.toJSONString(orders, SerializerFeature.DisableCircularReferenceDetect),Order.class));
            } else {
                return ResultUtils.error(MsgId.NOT_ANY_ORDER);
            }
        } else {
            return ResultUtils.error(MsgId.CUSTOMER_NOT_FOUND);
        }
    }

    /*订单详情
     *
     * */
    public Result getOrderById(int Id) {
        //首先是判断订单是否存在
        if (orderRepository.existsById(Id)) {
            Order order = orderRepository.findById(Id);
            if (order.getLogisticsOrder() != null) {
                List<LogisticsInfo> logisticsInfos = ToolUtils.getLogistics(order.getLogisticsOrder(), order.getLogistics());
                order.setLogisticsInfos(logisticsInfos);
            }
            if (order.getReturnLogisticsOrder() != null) {
                List<LogisticsInfo> logisticsInfos = ToolUtils.getLogistics(order.getReturnLogisticsOrder(), order.getReturnLogistics());
                order.setReturnLogisticsInfos(logisticsInfos);
            }

            return ResultUtils.success(order);
        } else {
            return ResultUtils.error(MsgId.NOT_ANY_ORDER);
        }
    }

    /*商家订单界面
     * 1.店铺名字(StoreName)
     * 获取Order的List
     * */
    public Result getOrderByStoreName(String StoreName) {
        if (businessRepository.existsByStoreName(StoreName)) {
            Business business = businessRepository.findByStoreName(StoreName);
            List<Order> orders = orderRepository.findAllByBusinessId(business.getId());
            if (orders.size() != 0) {
                return ResultUtils.success(JSON.parseArray(JSON.toJSONString(orders, SerializerFeature.DisableCircularReferenceDetect),Order.class));
            } else {
                return ResultUtils.error(MsgId.NOT_ANY_ORDER);
            }
        } else {
            return ResultUtils.error(MsgId.BUSINESS_NOT_FOUND);
        }
    }

    /*商家填写快递单号并修改状态
     *
     * */
    public Result AddLogisticsOrder(String LogisticsOrder, String Logistics, int orderId, int ReturnAddressId) {
        if (orderRepository.existsById(orderId)) {
            Order order = orderRepository.findById(orderId);
            order.setLogisticsOrder(LogisticsOrder);
            order.setLogistics(Logistics);
            order.setState("待收货");

            Address address = addressRepository.findById(ReturnAddressId);

            TemporaryAddress temporaryAddress = new TemporaryAddress();

            temporaryAddress.setArea(address.getArea());
            temporaryAddress.setAreaNum(address.getAreaNum());
            temporaryAddress.setProvince(address.getProvince());
            temporaryAddress.setProvinceNum(address.getProvinceNum());
            temporaryAddress.setCity(address.getCity());
            temporaryAddress.setCityNum(address.getCityNum());
            temporaryAddress.setTown(address.getTown());
            temporaryAddress.setTownNum(address.getTownNum());
            temporaryAddress.setDetailInfo(address.getDetailInfo());
            temporaryAddress.setReceiverName(address.getReceiverName());
            temporaryAddress.setPhoneNum(address.getPhoneNum());

            TemporaryAddress temporaryAddress1 = temporaryAddressRepository.saveAndFlush(temporaryAddress);

            order.setBusinessTemporaryAddress(temporaryAddress1);
            Customer customer = customerRepository.findById(order.getCustomerId());
            customer.setReceivedOrder(customer.getReceivedOrder() + 1);
            customer.setDeliveredOrder(customer.getDeliveredOrder() - 1);

            Order order1 = orderRepository.saveAndFlush(order);
            customerRepository.saveAndFlush(customer);

            if (order1.getLogisticsOrder().equals(LogisticsOrder)) {
                return ResultUtils.success(true);
            } else {
                return ResultUtils.error(MsgId.MODIFY_ERROR);
            }
        } else {
            return ResultUtils.error(MsgId.NOT_ANY_ORDER);
        }
    }

    /*用户确认收货并修改状态
     *
     * */
    public Result ReceivedOrder(int orderId) {
        if (orderRepository.existsById(orderId)) {
            Order order = orderRepository.findById(orderId);
            order.setState("租赁中");
            if (customerRepository.existsById(order.getCustomerId())) {
                Customer customer = customerRepository.findById(order.getCustomerId());
                customer.setLeasingOrder(customer.getLeasingOrder() + 1);
                customer.setReceivedOrder(customer.getReceivedOrder() - 1);
                customerRepository.saveAndFlush(customer);
            } else {
                return ResultUtils.error(MsgId.CUSTOMER_NOT_FOUND);
            }
            orderRepository.saveAndFlush(order);
            return ResultUtils.success(true);
        } else {
            return ResultUtils.error(MsgId.NOT_ANY_ORDER);
        }
    }

    /*用户填写快递单号并修改状态
     *
     * */
    public Result AddReturnLogisticsOrder(String ReturnLogisticsOrder, String ReturnLogistics, int orderId) {
        if (orderRepository.existsById(orderId)) {
            Order order = orderRepository.findById(orderId);
            order.setReturnLogisticsOrder(ReturnLogisticsOrder);
            order.setReturnLogistics(ReturnLogistics);
            order.setState("归还中");

            Customer customer = customerRepository.findById(order.getCustomerId());
            customer.setReturningOrder(customer.getReturningOrder() + 1);
            customer.setReturnedOrder(customer.getReturnedOrder() - 1);

            Order order1 = orderRepository.saveAndFlush(order);
            customerRepository.saveAndFlush(customer);

            if (order1.getReturnLogisticsOrder().equals(ReturnLogisticsOrder)) {
                return ResultUtils.success(true);
            } else {
                return ResultUtils.error(MsgId.MODIFY_ERROR);
            }
        } else {
            return ResultUtils.error(MsgId.NOT_ANY_ORDER);
        }
    }

    /*每日修改用户待归还
     *
     * */
    public void returnedOrder() throws ParseException {
        List<Order> orders = orderRepository.findAll();
        Date now = new Date();
        for (Order item :
                orders) {
            Date itemTime = new Date(new SimpleDateFormat("yyyy/mm/dd").parse(item.getLeaseEndTime()).getTime());
            if (item.getState().equals("租赁中") && itemTime.before(now)) {
                item.setState("待归还");
                Customer customer = customerRepository.findById(item.getCustomerId());
                customer.setReturnedOrder(customer.getReturnedOrder() + 1);
                customer.setLeasingOrder(customer.getLeasingOrder() - 1);
            }
        }
    }

    /*用户直接购买商品
     *
     * */
    public Result PurchaseSKU(int orderId) {
        if (orderRepository.existsById(orderId)) {
            Order order = orderRepository.findById(orderId);
            order.setState("已购买");
            orderRepository.saveAndFlush(order);
            return ResultUtils.success(true);
        } else {
            return ResultUtils.error(MsgId.NOT_ANY_ORDER);
        }
    }

    /*用户添加评论
     *
     * */
    public Result AddComment(Comment comment, int orderId) {
        if (orderRepository.existsById(orderId)) {
            Order order = orderRepository.findById(orderId);
            Point point = comment.getPoint();
            point.setCustomerid(order.getCustomerId());
            point.setSkuId(order.getSku().getId());
            comment.setPoint(pointRepository.saveAndFlush(point));
            comment.setCustomerId(order.getCustomerId());
            comment.setSkuId(order.getSku().getId());
            commentRepository.saveAndFlush(comment);
            return ResultUtils.success(true);
        } else {
            return ResultUtils.error(MsgId.NOT_ANY_ORDER);
        }
    }

    /*商家确认收货
     *
     * */
    public Result Received(int orderId) {
        if (orderRepository.existsById(orderId)) {
            Order order = orderRepository.findById(orderId);
            order.setState("已完成");
            orderRepository.saveAndFlush(order);
            return ResultUtils.success(true);
        } else {
            return ResultUtils.error(MsgId.NOT_ANY_ORDER);
        }
    }

}
